import React, { useState, useEffect } from 'react';
import Style from './WebsocketUse.module.less';
import '../../../common/common.css'

export default function WebsocketUse() {
    const [ws, setWs] = useState(null);
    const [message, setMessage] = useState('');
    const [serverMessage, setServerMassage] = useState('');
    const [chatHistory, setChatHistory] = useState([]);

    useEffect(() => {
        // 在组件挂载时建立 WebSocket 连接
        const newWs = new WebSocket('ws://localhost:8080'); // 替换为你的 WebSocket 服务器的 URL

        newWs.onopen = () => {
            console.log('WebSocket 连接已打开');
        };

        newWs.onmessage = (event) => {
            // // 处理接收到的消息
            console.log('接收到消息:', event.data);
            const receivedMessage = event.data;
            setChatHistory((prevHistory) => [...prevHistory, receivedMessage]);
            setServerMassage(receivedMessage);
        };

        newWs.onclose = () => {
            console.log('WebSocket 连接已关闭');
        };

        setWs(newWs);

        // 在组件卸载时关闭 WebSocket 连接
        return () => {
            newWs.close();
        };
    }, []); // 空的依赖数组确保该效果只运行一次

    const sendMessage = (message, type) => {
        console.log("ws", ws);
        if (ws.readyState === 3) {
            alert('WebSocket 连接已关闭，无法发送消息。请启动服务器重试！');
            return;
        }
        if (ws && message.trim() !== '') {
            ws.send(message, type);
        }
    };

    const handleSend = () => {
        sendMessage(message);
        setMessage('');
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            handleSend();
        }
    };

    return (
        <div>
            <button className='returnButton'><a href="/">点击返回主菜单</a></button>
            <div>
                <h1>
                    <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket">简介</a>
                </h1>
                <p>WebSocket 对象提供了用于创建和管理 WebSocket 连接，以及可以通过该连接发送和接收数据的 API。</p>
                <div style={{ textAlign: "left" }}>
                    <p>WebSocket.readyState</p>
                    <ul>
                        <li> 0 (WebSocket.CONNECTING)正在链接中</li>
                        <li> 1 (WebSocket.OPEN)已经链接并且可以通讯</li>
                        <li> 2 (WebSocket.CLOSING)连接正在关闭</li>
                        <li> 3 (WebSocket.CLOSED)连接已关闭或者没有链接成功</li>
                    </ul>
                </div>
            </div>
            <div className={Style.messageSend}>
                <div>
                    <input
                        type="text"
                        value={message}
                        onChange={(e) => setMessage(e.target.value)}
                        onKeyDown={handleKeyDown}
                        placeholder="对话框输入..."
                    />
                    <button onClick={handleSend}>发送</button>
                </div>
                <div className={Style.serverSend}>
                    <p>来自服务器的消息：{serverMessage}</p>
                </div>
            </div>

            <div style={{ clear: 'both' }}>
                <div>
                    {chatHistory.map((msg, index) => (
                        <div key={index}>{msg}</div>
                    ))}
                </div>
            </div>
        </div>
    )
}
